package com.code.aspectj.aspectj;

import android.os.Looper;

import com.code.aspectj.util.Executors;
import com.code.aspectj.util.ReflectUtils;
import com.code.aspectj.util.P;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import static com.code.aspectj.AppInterceptor.TAG;

/**
 * Created by RLZ
 * on 2021/12/8
 * 保证注解方法执行在主线程
 */
@Aspect
public class MainThreadAspect {

    @Pointcut("within(@com.code.aspectj.annotation.MainThread *)")
    public void withinAnnotatedClass() {
    }

    @Pointcut("execution(!synthetic * *(..)) && withinAnnotatedClass()")
    public void methodInsideAnnotatedType() {
    }

    @Pointcut("execution(@com.code.aspectj.annotation.MainThread * *(..)) || methodInsideAnnotatedType()")
    public void method() {
    }  //方法切入点

    @Around("method()")//在连接点进行方法替换
    public void aroundJoinPoint(final ProceedingJoinPoint joinPoint) throws Throwable {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            joinPoint.proceed();
        } else {
            P.d(TAG, ReflectUtils.getMethodDescribeInfo(joinPoint) + " \u21E2 [当前线程]:"
                    + Thread.currentThread().getName() + "，正在切换到主线程！");
            Executors.get().mainThread().execute(() -> {
                try {
                    joinPoint.proceed();
                } catch (Throwable e) {
                    P.e(TAG,e);
                }
            });
        }
    }

}
